package com.itany.nmms.controller;

import com.itany.mvc.annotation.RequestMapping;
import com.itany.mvc.annotation.ResponseBody;
import com.itany.mvc.util.CommonsMultipartFile;
import com.itany.nmms.constant.ResponseCodeConstant;
import com.itany.nmms.entity.ProductType;
import com.itany.nmms.exception.FileUploadErrorException;
import com.itany.nmms.exception.ProductExistException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.ProductService;
import com.itany.nmms.service.ProductTypeService;
import com.itany.nmms.util.ResponseResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 石小俊
 * @date 2023年11月10日 10:33
 */
@RequestMapping("/product")
public class ProductController {

    private ProductTypeService typeService = (ProductTypeService) ObjectFactory.getObject("typeService");
    private ProductService productService = (ProductService) ObjectFactory.getObject("productService");

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, HttpServletResponse response) {
        List<ProductType> types = typeService.findEnable();
        request.setAttribute("types", types);
        return "backend/productManager";
    }

    @ResponseBody
    @RequestMapping("/add")
    public ResponseResult add(HttpServletRequest request, HttpServletResponse response, List<CommonsMultipartFile> files) {
        ResponseResult result = new ResponseResult();

        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String typeId = request.getParameter("typeId");

        try {
            productService.addProduct(name, price, files, typeId, request.getSession());
            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        } catch (RequestParameterErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);
        } catch (ProductExistException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (FileUploadErrorException e) {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }

}
